<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import {
  Deployment,
  DeploymentCondition,
  LabelSelector
} from "@/views/domain/kubeHud/api/k8s/types";
import { useK8SApi } from "@/views/domain/kubeHud/api/k8s/k8s";
import { objectToList, timeTrans } from "@/views/domain/kubeHud/utils";
import RouterLinkBtn from "@/views/widgets/RouterLinkBtn/index.vue";
import KSpace from "../../components/KSpace.vue";
import KMentionText from "../../components/KMentionText.vue";
import { KubeHudRouterPath } from "@/views/domain/kubeHud/router";

type Prop = {
  namespace?: string;
  nodeName?: string;
  selector?: LabelSelector;
  deployments?: Deployment[];
};

const { deploymentRepo } = useK8SApi();
const props = defineProps<Prop>();
const emit = defineEmits(["update:deployments"]);

const deploymentList = ref<Deployment[]>();
const total = ref(0);
const nextToken = ref();
const loading = ref(false);

const labelSelector = computed(() => {
  const srcs = [
    props.nodeName ? `spec.nodeName=${props.nodeName}` : "",
    ...objectToList(props.selector).map(v => `${v.key}=${v.value}`)
  ];
  return srcs.filter(v => v !== "").join(",");
});

const loadDeploymentList = async () => {
  loading.value = true;
  try {
    const { ok, data } = await deploymentRepo.getDeploymentList({
      namespace: props.namespace,
      labelSelector: labelSelector.value,
      continue: nextToken.value
    });

    if (ok) {
      deploymentList.value = data.items;
      nextToken.value = data.metadata?.continue;
      total.value = data.metadata.remainingItemCount ?? data.items?.length;
      emit("update:deployments", deploymentList.value);
    }
  } catch (error) {
    console.log(error);
  }
  loading.value = false;
};

const getLastCondition = (deployment: Deployment): DeploymentCondition => {
  const conditions = deployment.status?.conditions;
  if (conditions && conditions.length > 0) {
    return conditions[conditions.length - 1];
  }
  return null;
};

const _deployStatus = (
  deployment: Deployment
): "running" | "updating" | "error" => {
  if (deployment.status?.availableReplicas === deployment.status?.replicas) {
    return "running";
  } else if (deployment.status?.updatedReplicas > 0) {
    return "updating";
  } else {
    return "error";
  }
};

const deployStatusStyle = (deployment: Deployment) => {
  const status = _deployStatus(deployment);
  if (status === "running") {
    return { backgroundColor: "var(--el-color-success)" };
  } else if (status === "updating") {
    return { backgroundColor: "var(--el-color-warning)" };
  } else {
    return { backgroundColor: "var(--el-color-danger)" };
  }
};
const deployStatusDesc = (deployment: Deployment) => {
  const status = _deployStatus(deployment);
  if (status === "running") {
    return `运行中(${deployment.status?.availableReplicas}/${deployment.status?.replicas})`;
  } else if (status === "updating") {
    return `更新中(${deployment.status?.readyReplicas ?? 0}/${deployment.status?.replicas})`;
  } else {
    return `错误(${deployment.status?.readyReplicas ?? 0}/${deployment.status?.replicas})`;
  }
};

onMounted(() => {
  loadDeploymentList();
});

watch(
  () => props.namespace,
  () => {
    loadDeploymentList();
  }
);
</script>

<template>
  <div v-loading="loading" class="w-full">
    <div />
    <el-table :data="deploymentList" table-layout="auto">
      <el-table-column prop="metadata.name" label="名称">
        <template #default="{ row }">
          <KSpace direction="column">
            <RouterLinkBtn
              :to="KubeHudRouterPath.DeploymentDetails"
              :query="{
                name: row.metadata.name,
                namespace: row.metadata.namespace
              }"
              :label="row.metadata.name"
            />
            <KMentionText
              v-if="row.status?.unavailableReplicas"
              :title="getLastCondition(row)?.reason"
              type="warning"
              show-icon
            />
          </KSpace>
        </template>
      </el-table-column>

      <el-table-column label="状态">
        <template #default="{ row }">
          <KSpace align="center" gap="5px">
            <div class="size-2 rounded-[50%]" :style="deployStatusStyle(row)" />
            <el-text>{{ deployStatusDesc(row) }}</el-text>
          </KSpace>
        </template>
      </el-table-column>

      <el-table-column prop="metadata.creationTimestamp" label="创建时间">
        <template #default="{ row }">
          {{ timeTrans(row.metadata.creationTimestamp, "YYYY-MM-DD HH:mm:ss") }}
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<style lang="scss" scoped></style>
